﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace AMVCommander
{
    public class Settings
    {
        string fPathSett;

        //**********************************************************************
        #region *** элементы со значениями по умолчанию ************************

        public bool DEBUG_MODE = false;
        public bool WRITE_LOG = false;

        public String FPathPlayer = "C:\\Program Files\\K-Lite Codec Pack\\Media Player Classic\\mpc-hc.exe";
        public String DPathHomeDir;
        public int LastTagsSize = 5;

        public int Frm_Left = 0;
        public int Frm_Top = 0;
        public int Frm_Width = 0;
        public int Frm_Height = 0;

        public List<Column> ClmL = new List<Column>();

        public int PeriodFindNew = 300; // период проверки новых файлов в домашней директории
        public int PeriodCheckExist = 120; // период быстрой проверки существующих файлов

        #endregion *** элементы со значениями по умолчанию *********************
        //**********************************************************************

        public Settings(string fPathSett)
        {
            this.fPathSett = fPathSett;

            //**********************************************************
            #region *** Сложные дефаулты *******************************

            ClmL.Add(new Column(ColumnType.Name, 150, true));
            ClmL.Add(new Column(ColumnType.Rating, 50, true));
            ClmL.Add(new Column(ColumnType.Tag, 250, true));
            ClmL.Add(new Column(ColumnType.KeyWords, 250, true));
            ClmL.Add(new Column(ColumnType.FPath, 150, true));
            ClmL.Add(new Column(ColumnType.Len, 70, true));
            ClmL.Add(new Column(ColumnType.Author, 150, true));
            ClmL.Add(new Column(ColumnType.Music, 150, true));
            ClmL.Add(new Column(ColumnType.Anime, 150, true));
            ClmL.Add(new Column(ColumnType.Awards, 150, true));

            #endregion *** Сложные дефаулты ****************************
            //**********************************************************

            if (File.Exists(fPathSett))
            {
                String[] strl = File.ReadAllLines(fPathSett, Encoding.UTF8);
                for (int i = 0; i < strl.Length; i++)
                {
                    string[] sl = strl[i].Split(new Char[1] { '=' }, 2);
                    if (sl.Length < 2) continue;
                    string key = sl[0].Trim();
                    string val = sl[1].Trim();

                    //**********************************************************
                    #region *** Загрузка элементов *****************************

                    if (key == "FPathPlayer") FPathPlayer = val;
                    if (key == "DPathHomeDir") DPathHomeDir = val;
                    if (key == "Columns") LoadColumnList(val);
                    if (key == "LastTagsSize") { int tmp; if (int.TryParse(val, out tmp)) { if (tmp >= 0) LastTagsSize = tmp; } }

                    if (key == "Frm_Top") { int tmp; if (int.TryParse(val, out tmp)) { if (tmp >= 0) Frm_Top = tmp; } }
                    if (key == "Frm_Left") { int tmp; if (int.TryParse(val, out tmp)) { if (tmp >= 0) Frm_Left = tmp; } }
                    if (key == "Frm_Width") { int tmp; if (int.TryParse(val, out tmp)) { if (tmp >= 0) Frm_Width = tmp; } }
                    if (key == "Frm_Height") { int tmp; if (int.TryParse(val, out tmp)) { if (tmp >= 0) Frm_Height = tmp; } }

                    if (key == "DEBUG_MODE") { DEBUG_MODE = val == "1"; }
                    if (key == "WRITE_LOG") { WRITE_LOG = val == "1"; }

                    if (key == "PeriodFindNew") { int tmp; if (int.TryParse(val, out tmp)) { if (tmp > 0) PeriodFindNew = tmp; } }
                    if (key == "PeriodCheckExist") { int tmp; if (int.TryParse(val, out tmp)) { if (tmp > 0) PeriodCheckExist = tmp; } }

                    #endregion *** Загрузка элементов *****************************
                    //**********************************************************
                }
            }
        }

        public void Save()
        {
            List<string> strL = new List<string>();

            #region *** Сохранение элементов ***************************

            strL.Add("FPathPlayer = " + FPathPlayer);
            strL.Add("DPathHomeDir = " + DPathHomeDir);
            strL.Add("Columns = " + ColumnListToString());
            strL.Add("LastTagsSize = " + LastTagsSize.ToString());

            strL.Add("Frm_Top = " + Frm_Top.ToString());
            strL.Add("Frm_Left = " + Frm_Left.ToString());
            strL.Add("Frm_Width = " + Frm_Width.ToString());
            strL.Add("Frm_Height = " + Frm_Height.ToString());

            strL.Add("DEBUG_MODE = " + (DEBUG_MODE ? "1" : "0"));
            strL.Add("WRITE_LOG = " + (WRITE_LOG ? "1" : "0"));

            strL.Add("PeriodFindNew = " + PeriodFindNew.ToString());
            strL.Add("PeriodCheckExist = " + PeriodCheckExist.ToString());

            #endregion *** Сохранение элементов ************************

            File.WriteAllLines(fPathSett, strL.ToArray(), Encoding.UTF8);
        }

        void LoadColumnList(string val)
        {
            List<Column> newClmL = new List<Column>();
            try
            {
                string[] sl = val.Split(';');
                if (sl.Length != ClmL.Count) return; // если количество элементов не совпадает, выходим
                for (int i = 0; i < sl.Length; i++)
                {
                    string[] ssl = sl[i].Split(',');
                    ColumnType Tp = (ColumnType)Convert.ToInt32(ssl[0].Trim());
                    int W = Convert.ToInt32(ssl[1].Trim());
                    if (W < 50) W = 50;
                    if (W > 1000) W = 1000;
                    bool Vis = ssl[2].Trim().ToUpper() == "TRUE";

                    newClmL.Add(new Column(Tp, W, Vis));
                }
                ClmL = newClmL;
            }
            catch { }
        }

        string ColumnListToString()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < ClmL.Count; i++)
            {
                if (i > 0) sb.Append(";");
                sb.Append(((int)ClmL[i].Tp).ToString());
                sb.Append(",");
                sb.Append(ClmL[i].Width.ToString());
                sb.Append(",");
                sb.Append(ClmL[i].Visible ? "true" : "false");
            }
            return sb.ToString();
        }

        void LoadIntList(List<int> lst, string val)
        {
            List<int> mas = new List<int>();
            try
            {
                string[] slMas = val.Split(';');
                for (int i = 0; i < slMas.Length; i++)
                    mas.Add(Convert.ToInt32(slMas[i].Trim()));

                if (mas.Count > 0)
                {
                    lst.Clear();
                    for (int i = 0; i < mas.Count; i++) lst.Add(mas[i]);
                }
            }
            catch { }
        }

        string IntListToString(List<int> lst)
        {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < lst.Count; j++)
            {
                if (j > 0) sb.Append(";");
                sb.Append(lst[j].ToString());
            }
            return sb.ToString();
        }
    }

    public enum ColumnType { Name, FPath, Len, Tag, Author, Music, Anime, Awards, KeyWords, Rating }

    public class Column
    {
        public ColumnType Tp;
        public int Width;
        public bool Visible;

        public string Flt = "";


        public string Name
        {
            get
            {
                switch (Tp)
                {
                    case ColumnType.Name: return "Название";
                    case ColumnType.FPath: return "Путь к файлу";
                    case ColumnType.Len: return "Размер";
                    case ColumnType.Rating: return "Оценка";
                    case ColumnType.Tag: return "Теги";
                    case ColumnType.Author: return "Авторы";
                    case ColumnType.Music: return "Музыка";
                    case ColumnType.Anime: return "Аниме";
                    case ColumnType.Awards: return "Конвенты и награды";
                    case ColumnType.KeyWords: return "Ключевые слова";
                }
                throw new Exception("Ошибка нахождения имени столбца по его типу. Неизвестный тип " + Tp.ToString());
            }
        }

        public Column(ColumnType Tp, int Width, bool Visible)
        {
            this.Tp = Tp;
            this.Width = Width;
            this.Visible = Visible;
        }

    }

}
